package com.infolab.aims.common;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

public class QueryHelper {
	
	private  String selectSql;
	
	private  String orderSql;
	
	private  List<String> whereSql = new ArrayList<String>();
	public QueryHelper() {
	
	}
	
	public void order(String order)
	{
		setOrderSql(order);
	}
	
	public void select(String select)
	{
		setSelectSql(select);
	}
	
	public  void  where(String where)
	{
		List<String> whereSql = getWhereSql();
		whereSql.add(where);
		
	}
	


	public  String getSelectSql() {
		return selectSql;
	}


	public void setSelectSql(String selectSql) {
		this.selectSql = selectSql;
	}

	public void setOrderSql(String orderSql) {
		this.orderSql = orderSql;
	}

	public  String getOrderSql() {
		return orderSql;
	}


	public  List<String> getWhereSql() {
		return whereSql;
	}

	
	
	public String getResultSql()
	{
		String sql = selectSql;
		if(whereSql.size()!=0)
		{
			String where = StringUtils.join(whereSql.toArray(new String[0])," and ");
			if(StringUtils.contains(sql, "where"))
				sql+=" and "+where;
			else
				sql+=" where "+where;
		}
		if(orderSql!=null)
		{
			sql+=" order by "+orderSql;
		}
		
		return sql;
	}
	
	public String getCountSql()
	{
		String sql = selectSql;
		
		Pattern pattern = Pattern.compile("select (.*) from",Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(selectSql);
		
		StringBuffer sb = new StringBuffer();
		matcher.find();
		System.out.println(matcher.group(1));
		
		sql=StringUtils.replaceOnce(sql,matcher.group(1),"count(*)");
		//sql = sb.toString();
		
		if(whereSql.size()!=0)
		{
			String where = StringUtils.join(whereSql.toArray(new String[0])," and ");
			if(StringUtils.contains(sql, "where"))
				sql+=" and "+where;
			else
				sql+=" where "+where;
		}
		
		return sql;
	}
	

}
